package com.example.flasksale.service;

import com.example.flasksale.dao.OrderDao;
import com.example.flasksale.entity.Order;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class OrderService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private OrderDao orderDao;

    public boolean order(Integer productId, Long userId) {

        // 获取库存
        String s = redisTemplate.opsForValue().get(productId + "");
        if (Integer.parseInt(s) <= 0) {
            System.out.println("没有库存了");
            return false;
        }

        Order order = new Order();
        order.setAmount(new BigDecimal(9999999));
        order.setStatus(OrderStatus.UNPAID.ordinal());
        order.setProductId(Long.valueOf(productId));
        order.setUserId(userId);
        order.setCreateTime(new Date());
        order.setModifyTime(order.getCreateTime());

        rocketMQTemplate.asyncSend(Consts.TOPIC_ORDER, order, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                // 库存前面已经减过了，不用再处理了
            }

            @Override
            public void onException(Throwable throwable) {
                // 消息发送失败，库存要恢复
//                redisTemplate.opsForValue().increment(productId + "");
            }
        });
        return true;
    }

    public void add(Order order) {
        orderDao.insertOne(order);
    }

    public int findById(Long orderId) {
        return orderDao.findById(orderId);
    }

    public void cancel(Long orderId) {
        orderDao.cancel(orderId);
    }


}
